<?php

declare(strict_types=1);
/**
 * 创建人 : Forpastime
 *
 * @link     http://hypercmf.com
 * @document https://hyperf.wiki
 * @contact  forpastime@qq.com
 * @git  https://gitee.com/hypercmf/hypercmf1.0.git
 */
namespace App\Controller\Api;

use App\Utils\Result;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Filesystem\FilesystemFactory;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use League\Flysystem\Filesystem;
use App\Controller\Admin\FileController as File;

/**
 * @Controller(prefix="api/file")
 *
 * Class FileController
 */
class FileController
{
    /**
     * @Inject()
     * @var RequestInterface
     */
    protected $request;

    /**
     * @RequestMapping(path="upload", methods={"get", "post"})
     *
     */
    public function upload()
    {
        $fileController = new File();
        $file = $this->request->file("file");

        $categoryId = $this->request->input('category_id',0);
        $data = $fileController->uploadAction($file,$categoryId);
        return Result::success($data);
    }

    /**
     * @PostMapping(path="upload/oss")
     */
    public function uploadOSS(FilesystemFactory $factory)
    {
        $file = $this->request->file('file');

        // throw new ServerErrorHttpException('bbb',403);
        if (empty($file)) {
            return $this->error('文件不能为空');
        }
        $oss = $factory->get('oss');

        $allowedArr = ['jpeg', 'gif', 'jpg', 'png', 'mp3', 'wav', 'm4a'];
        $ext = strtolower($file->getExtension());
        if (! in_array($ext, $allowedArr)) {
            return $this->error($ext . '格式文件不允许上传');
        }
        $path = 'uploads/' . time() . mt_rand(1000, 9999) . '.' . $ext;
        $oss->write($path, file_get_contents($file->getRealPath()));
        // 返回地址
        $res = [
            'path' => env('OSS_PROTOCOL') . env('OSS_BUCKET') . '.' . env('OSS_ENDPOINT') . '/' . $path,
        ];
        return Result::success($res);
    }
}
